<template>
  <div>
    <el-card>
      <el-form
        ref="elFormRef"
        :model="formConfig"
        label-position="right"
        :rules="ruleFormConfig"
        :inline="true"
        label-width="100px"
      >
        <el-form-item label="数据主题:" prop="topicId" style="width:18%">
          <el-select v-model="formConfig.topicId" style="width:100%" @change="getTopicCode">
            <el-option v-for="item in adsTopics" :key="item.id" :value="item.ID" :label="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="主题编码:" prop="topicCode" style="width:18%">
          <el-input v-model="formConfig.topicCode" :disabled="true" style="width:100%" />
        </el-form-item>

        <el-form-item label="服务名称:" prop="name" style="width:18%">
          <el-input v-model="formConfig.name" placeholder="请输入中文" style="width:100%" />
        </el-form-item>

        <el-form-item label="服务编码:" prop="code" style="width:18%">
          <el-input v-model="formConfig.code" placeholder="请输入英文" style="width:100%" />
        </el-form-item>

        <el-form-item label="接口类型:" prop="apiType" style="width:18%">
          <el-select v-model="formConfig.apiType" style="width:100%">
            <el-option v-for="item in apiType" :key="item.id" :value="item.label" :label="item.label" />
          </el-select>
        </el-form-item>

        <el-form-item label="请求方式:" prop="requestType" style="width:18%">
          <el-select v-model="formConfig.requestType" style="width:100%">
            <el-option v-for="item in requestType" :key="item.id" :value="item.label" :label="item.label" />
          </el-select>
        </el-form-item>

        <el-form-item label="是否启用:" prop="status" style="width:18%">
          <el-switch v-model="formConfig.status" style="width:194px" active-color="#13ce66" inactive-color="#ff4949" active-text="是" inactive-text="否" clearable />
        </el-form-item>

        <el-form-item label="已选择数据表:" style="width:100%">
          <template v-for="(item,index) in srcTbList" :key="item">
            <template v-if="srcTbList.length>0 && index<(srcTbList.length) && index>0">
              <el-select v-model="item.joinType" style="width:7%" placeholder="连接方式">
                <el-option v-for="joinType in joinTypeList" :key="joinType.id" :value="joinType.label" :label="joinType.label" />
              </el-select>
            </template>
            <el-button type="success">{{ item.srcTbName }}</el-button>
            <el-button :icon="Delete" type="primary" @click="delSrcTb(item.srcTbId)" />
            <template v-if="srcTbList.length>0 && index<(srcTbList.length) && index>0">
              <span style="margin:5px;">on</span>
              <el-select v-model="srcTbList[index-1].joinOn" style="width:7%" placeholder="选择列名">
                <el-option v-for="joinOn in srcTbList[index-1].colList" :key="joinOn" :value="joinOn" :label="joinOn" />
              </el-select>
              <span style="margin:5px;">=</span>
              <el-select v-model="item.joinOn" style="width:7%" placeholder="选择列名">
                <el-option v-for="joinOn in item.colList" :key="joinOn" :value="joinOn" :label="joinOn" />
              </el-select>
            </template>

          </template>
          <el-form-item>
            <el-button style="margin:5px;" type="primary" icon="plus" @click="openDialog">新增数据源表</el-button>
          </el-form-item>
        </el-form-item>

      </el-form>
    </el-card>

    <el-dialog v-model="dialogFormVisible" :before-close="closeDialog" title="选择源数据">
      <el-form
        ref="elFormRef"
        :model="formTb"
        label-position="right"
        :rules="ruleDialog"
        label-width="100px"
        :inline="true"
      >
        <el-form-item label="源schema:" prop="srcSchema" style="width:40%">
          <el-select v-model="formTb.srcSchema" clearable style="width:100%" placeholder="请选择源schema">
            <el-option v-for="item in schemaList" :key="item" :value="item" :label="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="源表名称:" prop="srcTbId" style="width:40%">
          <el-select v-model="formTb.srcTbId" clearable style="width:100%" filterable placeholder="请选择源数据表">
            <el-option v-for="item in odsTbs" :key="item.id" :value="item.ID" :label="item.odsTbName" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="addSrcTb">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-row v-if="srcTbList" :gutter="20">
      <el-col :span="7">
        <el-card>
          <template #header>
            <div class="card-header" style="text-align:center">
              <span>数据选择</span>
            </div>
          </template>

          <template v-for="item in srcTbList" :key="item">
            <div style="text-align:center">
              <span>表名: {{ item.srcTbName }}</span><el-icon style="float: right"><DArrowRight /></el-icon>
            </div>
            <el-table
              ref="multipleTable"
              style="width: 100%"
              :size="'small'"
              border
              :cell-style="{padding:'0px'}"
              :header-cell-style="{background:'#a3c6d2',color:'#849ba1',padding:'0px'}"
              tooltip-effect="dark"
              :data="item.srcFlds"
              row-key="ID"
            >
              <el-table-column align="left" label="列类型" prop="odsColType" :show-overflow-tooltip="true" />
              <el-table-column align="left" label="列标签" prop="odsColComment" :show-overflow-tooltip="true" />
              <el-table-column align="left" label="列名称" prop="odsColName" :show-overflow-tooltip="true" />
              <el-table-column align="left" label="选择" width="60" fixed="right">
                <template #default="scope">
                  <el-icon @click="selectFld(scope.row)"><ArrowRightBold /></el-icon>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-card>
      </el-col>

      <el-col :span="10">
        <el-card>
          <template #header>
            <div class="card-header" style="text-align:center">
              <span>接口数据</span>
            </div>
          </template>

          <div style="text-align:center">
            <el-icon style="float: left"><DArrowLeft /></el-icon> <span>接口名称: {{ formConfig.code }}</span>
          </div>

          <el-table
            ref="multipleTable"
            style="width: 100%"
            border
            :size="'small'"
            :cell-style="{padding:'0px'}"
            :header-cell-style="{background:'#a3c6d2',color:'#849ba1',padding:'0px'}"
            tooltip-effect="dark"
            :data="adsFldTb"
            row-key="ID"
          >
            <el-table-column align="left" label="删除" width="60" fixed="left">
              <template #default="scope">
                <el-icon @click="deleteAdsFld(scope.row.srcFldId)"><ArrowLeftBold /></el-icon>
              </template>
            </el-table-column>
            <el-table-column align="left" label="源表ID" prop="srcTbId" width="80" />
            <el-table-column align="left" label="源表列名" prop="srcFldName" :show-overflow-tooltip="true" />
            <el-table-column align="left" label="列类型" prop="adsFldType" :show-overflow-tooltip="true" />
            <el-table-column align="left" label="接口列名" prop="adsFldName" width="180">
              <template #default="{row}">
                <el-input v-model="row.adsFldName" />
              </template>
            </el-table-column>

          </el-table>
        </el-card>
      </el-col>

      <el-col :span="4">
        <el-card>
          <template #header>
            <div class="card-header" style="text-align:center">
              <span>SQL预览</span>
            </div>
          </template>

          <template v-if="adsFldTb">
            <span>select{{ space }}<br></span>
            <template v-for="(item,idx) in adsFldTb" :key="item">
              <span v-if="idx<adsFldTb.length-1">t{{ item.srcTbId }}.{{ item.srcFldName }} {{ item.adsFldName }},<br></span>
              <span v-else>t{{ item.srcTbId }}.{{ item.srcFldName }} {{ item.adsFldName }}{{ space }}<br></span>
            </template>

            <span>from{{ space }}<br></span>
            <template v-for="(item, index) in srcTbList" :key="item">
              <template v-if="item.joinType">
                {{ item.joinType }}<br>
              </template>
              {{ item.srcTbName }} t{{ item.srcTbId }}<br>
              <template v-if="item.joinOn && index>0">
                <span>on{{ space }}<br></span>
                t{{ srcTbList[index-1].srcTbId }}.{{ srcTbList[index-1].joinOn }}=t{{ item.srcTbId }}.{{ item.joinOn }}<br>
              </template>
            </template>
            where ...<br>
            <template />
          </template>
        </el-card>
      </el-col>

      <el-col :span="3">
        <el-card>
          <template #header>
            <div class="card-header" style="text-align:center">
              <span>接口示例</span>
            </div>
          </template>

          数据请求方式:{{ formConfig.requestType }}<br><br>
          数据请求示例:<br>
          {<br>
          topic:{{ formConfig.topicCode }}<br>
          name:{{ formConfig.code }}<br>
          param:[{<br>
          colName:xxx<br>
          condition:= '大/小/等/不等'<br>
          colValue:xxx<br>
          }]<br>
          }<br><br>
          数据响应示例:<br>
          {<br>
          code:{{ 200 }}<br>
          data:{<br>
          {{ formConfig.code }}{...}<br>
          }<br>
          msg:"..."<br>
          }<br>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  name: 'AdsConfig'
}
</script>

<script setup>
import {
  createAdsConfig,
  deleteAdsConfig,
  deleteAdsConfigByIds,
  updateAdsConfig,
  findAdsConfig,
  getAdsConfigList,
} from '@/api/adsConfig'

import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive } from 'vue'
import { getAllAdsTopics } from '@/api/adsTopic'
import { getAllOdsDbTables } from '@/api/odsDbTable'
import { getOdsFldsByTbId } from '@/api/odsDbField'
import { ArrowLeftBold, ArrowRightBold, DArrowLeft, Delete } from '@element-plus/icons-vue'
import { getDict } from '@/utils/dictionary'
const sw = ref(true)
const formConfig = ref({
  topicId: '',
  topicCode: '',
  name: '',
  code: '',
  apiType: '',
  requestType: '',
  status: false,
  srcTbIds: [],
  adsFld: [],
})
const space = ref(' ')
const formTb = ref({
  srcSchema: '',
  srcTbId: '',
  srcTbName: '',
  srcFlds: [],
  joinType: '',
  joinOn: '',
  colList: [],
})
const formTbReset = async() => {
  formTb.value = {
    srcSchema: '',
    srcTbId: '',
    srcTbName: '',
    srcFlds: [],
    joinType: '',
    joinOn: '',
    colList: [],
  }
}
const srcTbList = ref([])

const adsFld = ref({
  'srcTbId': '',
  'srcTbName': '',

  'srcFldId': '',
  'srcFldName': '',
  'srcFldType': '',
  'srcFldLen': '',

  'adsFldName': '',
  'adsFldType': '',
  'adsFldLen': '',
})
const adsFldReset = async() => {
  adsFld.value = {
    'srcTbId': '',
    'srcTbName': '',

    'srcFldId': '',
    'srcFldName': '',
    'srcFldType': '',
    'srcFldLen': '',

    'adsFldName': '',
    'adsFldType': '',
    'adsFldLen': '',
  }
}
const formTbDataList = ref([])
const formFldData = ref({
  apiId: 0,
  srcSchema: '',
  srcTbName: '',
  srcFldName: '',
  srcFldType: '',
  srcFldLen: 0,
  adsFldName: '',
  adsFldType: '',
  adsFldLen: 0,
  joinType: '',
  joinTbName: '',
  joinColName: '',
})
const joinTypeList = ref([])
const getJoinTypeList = async() => {
  joinTypeList.value = await getDict('joinType')
}
const apiType = ref([])
const getApiType = async() => {
  apiType.value = await getDict('apiType')
}

const requestType = ref([])
const getRequestType = async() => {
  requestType.value = await getDict('requestType')
}
const tableFld = ref()

const schemaList = ref(
  ['xidw-ods']
)

const getTopicCode = async(data) => {
  for (let i = 0; i < adsTopics.value.length; i++) {
    if (data === adsTopics.value[i].ID) {
      formConfig.value.topicCode = adsTopics.value[i].code
    }
  }
}

const ruleFormConfig = reactive({
  topicId: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  }],
  apiType: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  }],
  requestType: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  }],
  name: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  }],
  code: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  }],
})

const ruleDialog = reactive({
  srcSchema: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  }],
  srcTbName: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  }],
})

const elFormRef = ref()

const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({})

const onReset = () => {
  searchInfo.value = {}
  getTableData()
}

const onSubmit = () => {
  page.value = 1
  pageSize.value = 10
  if (searchInfo.value.serviceType === '') {
    searchInfo.value.serviceType = null
  }
  if (searchInfo.value.status === '') {
    searchInfo.value.status = null
  }
  getTableData()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

const getTableData = async() => {
  const table = await getAdsConfigList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

getTableData()


const setOptions = async() => {
}

setOptions()

const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const deleteRow = (row) => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteAdsConfigFunc(row)
  })
}

const deleteVisible = ref(false)

const deleteSelectedRow = async() => {
  const ids = []
  if (multipleSelection.value.length === 0) {
    ElMessage({
      type: 'warning',
      message: '请选择要删除的数据'
    })
    return
  }
  multipleSelection.value &&
  multipleSelection.value.map(item => {
    ids.push(item.ID)
  })
  const res = await deleteAdsConfigByIds({ ids })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    if (tableData.value.length === ids.length && page.value > 1) {
      page.value--
    }
    deleteVisible.value = false
    getTableData()
  }
}

const type = ref('')

const updateAdsConfigFunc = async(row) => {
  const res = await findAdsConfig({ ID: row.ID })
  type.value = 'update'
  if (res.code === 0) {
    formConfig.value = res.data.readsConfig
    dialogFormVisible.value = true
  }
}

const deleteAdsConfigFunc = async(row) => {
  const res = await deleteAdsConfig({ ID: row.ID })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    if (tableData.value.length === 1 && page.value > 1) {
      page.value--
    }
    getTableData()
  }
}

const dialogFormVisible = ref(false)

const openDialog = async() => {
  dialogFormVisible.value = true
}

const closeDialog = async() => {
  dialogFormVisible.value = false
  await formTbReset()
}
const enterDialog = async() => {
  elFormRef.value?.validate(async(valid) => {
    if (!valid) return
    let res
    switch (type.value) {
      case 'create':
        res = await createAdsConfig(formConfig.value)
        break
      case 'update':
        res = await updateAdsConfig(formConfig.value)
        break
      default:
        res = await createAdsConfig(formConfig.value)
        break
    }
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '创建/更改成功'
      })
      await closeDialog()
      await getTableData()
    }
  })
}
const addSrcTb = async() => {
  if (formTb.value.srcSchema && formTb.value.srcTbId) {
    for (let i = 0; i < srcTbList.value.length; i++) {
      if (formTb.value.srcSchema === srcTbList.value[i].srcSchema &&
          formTb.value.srcTbId === srcTbList.value[i].srcTbId) {
        ElMessage({
          type: 'success',
          message: '此表已经选择'
        })
        await formTbReset()
        return
      }
    }
    const res = await getOdsFldsByTbId(formTb.value.srcTbId)
    if (res.code === 0) {
      formTb.value.srcFlds = res.data.odsFlds
      for (const oneFld of formTb.value.srcFlds) {
        formTb.value.colList.push(oneFld.odsColName)
      }
    } else {
      ElMessage({
        type: 'info',
        message: '根据表ID获取ODS字段信息失败'
      })
    }
    for (let i = 0; i < odsTbs.value.length; i++) {
      if (odsTbs.value[i].ID === formTb.value.srcTbId) {
        formTb.value.srcTbName = odsTbs.value[i].odsTbName
      }
    }
    if (!formTb.value.srcTbName) {
      ElMessage({
        type: 'info',
        message: '未能查询到此表'
      })
      return
    }
    srcTbList.value.push(formTb.value)
  } else {
    ElMessage({
      type: 'info',
      message: '请填写完整信息'
    })
  }
  await closeDialog()
}
const delSrcTb = async(data) => {
  for (let i = 0; i < srcTbList.value.length; i++) {
    if (srcTbList.value[i].srcTbId === data) {
      srcTbList.value = srcTbList.value.filter(t => t.srcTbId !== data)
      await deleteAdsFldTb(data)
    }
  }
}

const adsTopics = ref([])
const getAdsTopic = async() => {
  const res = await getAllAdsTopics()
  if (res.code === 0) {
    adsTopics.value = res.data.adsTopics
  }
}

const odsTbs = ref()
const getOdsTb = async() => {
  const res = await getAllOdsDbTables()
  if (res.code === 0) {
    odsTbs.value = res.data.odsDbTable
  } else {
    ElMessage({
      type: 'info',
      message: '获取ODS表名称失败'
    })
  }
}
const odsFlds = ref()
const getOdsFlds = async(data) => {
  const res = await getOdsFldByTbId(data)
  if (res.code === 0) {
    odsFlds.value = res.data.odsFlds
  } else {
    ElMessage({
      type: 'info',
      message: '根据表ID获取ODS字段信息失败'
    })
  }
}

const adsFldTb = ref([])
const selectRow = (row) => {
}
const selectFld = async(data) => {
  for (const one of adsFldTb.value) {
    if (one.srcFldId === data.ID) {
      return
    }
  }
  adsFld.value.srcTbId = data.srcTbId
  adsFld.value.srcFldId = data.ID
  adsFld.value.srcTbName = data.odsTbName
  adsFld.value.srcFldName = data.odsColName
  adsFld.value.srcFldType = data.odsColType

  adsFld.value.adsFldName = data.odsColName
  adsFld.value.adsFldType = data.odsColType
  adsFldTb.value.push(adsFld.value)
  await adsFldReset()
  selectRow(data)
}

const deleteAdsFld = async(data) => {
  for (let i = 0; i < adsFldTb.value.length; i++) {
    if (adsFldTb.value[i].srcFldId === data) {
      adsFldTb.value = adsFldTb.value.filter(t => t.srcFldId !== data)
    }
  }
}

const deleteAdsFldTb = async(data) => {
  for (let i = 0; i < adsFldTb.value.length; i++) {
    if (adsFldTb.value[i].srcTbId === data) {
      adsFldTb.value = adsFldTb.value.filter(t => t.srcTbId !== data)
    }
  }
}

const init = () => {
  getOdsTb()
  getAdsTopic()
  getApiType()
  getRequestType()
  getJoinTypeList()
}
init()

</script>

<style lang="scss" scoped>
.el-card:deep(.el-card__header) {
  background: linear-gradient(to bottom, #98c6ec, #f6f8f7);
}
</style>
